import { AuthRole } from '@/headers/admin/auth.h';
import  adminStore from '@/store/admin';
import { GetUserActorRoleAction } from '@/store/admin/action';
import { AuthError } from '@/utils/errors';
import {NavigationGuardWithThis} from 'vue-router'
import router from '../admin';

declare module 'vue-router' {
    export interface RouterOptions {
        from?:RouteLocationNormalized|null,
        to?:RouteLocationNormalized|null
    }
}

type Guard = NavigationGuardWithThis<undefined>


export function recordRouter():Guard {
    return async function (to,from,next) {
        router.options.from = from
        router.options.to = to;
        await new Promise((res)=>{
            next(res)
        })
        router.options.from = null;
        router.options.to = null;

    }
}
export function titleGuard(prefix:string):Guard {
    return async function (to,_from,next) {
        let title = to.name;
        if(to.meta.title && typeof to.meta.title === 'string') {
            title = to.meta.title
        }
        if(title) {
            window.document.title = `${prefix}${String(title)}`
        }
        return next();
    }
}


export function authGuard():Guard {
    return async function(to,_form) {
        if(typeof to.meta.auth === 'number') {
            if(to.meta.auth & AuthRole.Guest) {
                return
            }

            const role = await GetUserActorRoleAction.getInstance().call(adminStore)
            if(to.meta.auth & AuthRole.Student) {
                if(!(role & (AuthRole.Student|AuthRole.Admin))) {
                    return new AuthError();
                }
            }
            if(to.meta.auth & AuthRole.Leader) {
                if(!(role & (AuthRole.Leader | AuthRole.Admin))) {
                    return new AuthError();
                }
            }
            if(to.meta.auth & AuthRole.Admin) {
                if(!(role & (AuthRole.Admin))) {
                    return new AuthError();
                }
            }
            return;
        }
    }
}